package org.groupg.project;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.util.DaemonThreadFactory;

public class DisruptorDependencyExample {

    // 定义事件类
    static class TaskEvent {
        private int taskId;

        public int getTaskId() {
            return taskId;
        }

        public void setTaskId(int taskId) {
            this.taskId = taskId;
        }
    }

    // 定义事件处理器 A
    static class TaskHandlerA implements com.lmax.disruptor.EventHandler<TaskEvent> {
        private final String name;

        public TaskHandlerA(String name) {
            this.name = name;
        }

        @Override
        public void onEvent(TaskEvent event, long sequence, boolean endOfBatch) {
            System.out.println(name + " processing task: " + event.getTaskId());
            // 模拟处理时间
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 定义 Disruptor 的缓冲区大小
        int bufferSize = 1024;

        // 创建 Disruptor
        Disruptor<TaskEvent> disruptor = new Disruptor<>(
                TaskEvent::new, bufferSize, DaemonThreadFactory.INSTANCE);

        // 创建两个 TaskHandlerA 实例
        TaskHandlerA handlerA1 = new TaskHandlerA("HandlerA1");
        TaskHandlerA handlerA2 = new TaskHandlerA("HandlerA2");

        // 设置依赖关系：handlerA1 -> handlerA2
        disruptor.handleEventsWith(handlerA1).then(handlerA2);

        // 启动 Disruptor
        RingBuffer<TaskEvent> ringBuffer = disruptor.start();

        // 发布事件
        for (int i = 0; i < 10; i++) {
            long sequence = ringBuffer.next();
            try {
                TaskEvent event = ringBuffer.get(sequence);
                event.setTaskId(i);
            } finally {
                ringBuffer.publish(sequence);
            }
            Thread.sleep(100); // 模拟事件发布的间隔
        }

        // 关闭 Disruptor
        disruptor.shutdown();
    }
}